package org.akomantoso.core.io.util;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.akomantoso.core.data.BodyTypeElement;
import org.akomantoso.core.data.ComponentRef;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;
import org.akomantoso.core.io.util.group.HierElementsGroup;
import org.akomantoso.core.util.MapUtil;

/**
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 */
public class BodyTypeElementUtil {

	private BodyTypeElementUtil() {
	}

	static final Map<String, Instantiator<BodyTypeElement>> MAP;

	private static BodyTypeElement instantiate(String elementName) {

		final Instantiator<? extends BodyTypeElement> instatiator = MAP.get(elementName);
		if (instatiator == null) {
			throw new RuntimeException("Tag [" + elementName + "] not supported for BodyTypeElement ?!?");
		}
		return instatiator.instantiate();

	}

	public static void read(Input in, List<BodyTypeElement> elements) throws IOException {
		final String localName = in.getLocalName();
		in.readNextStartElement();
		
		BodyTypeElement element = null;
		int eventType = in.getEventType();
		while (true) {
			switch (eventType) {
			case InputConstants.START_ELEMENT:
				elements.add(element = instantiate(in.getLocalName()));
				element.readExternal(in);
				break;
			case InputConstants.END_ELEMENT:
				if (localName.equals(in.getLocalName())) {
					return;
				}
			}
			eventType = in.readNext();
		}
	}

	static {
		Map<String, Instantiator<BodyTypeElement>> temp = new HashMap<String, Instantiator<BodyTypeElement>>();
		MapUtil.copy(HierElementsGroup.MAP, temp);
		temp.put(ComponentRef.ELEMENT, new Instantiator<BodyTypeElement>() {
			public ComponentRef instantiate() {
				return new ComponentRef();
			}
		});
		MAP = Collections.unmodifiableMap(temp);
	}

}